// page/component/payment/payment.js
const app = getApp();
const { request } = require('../../../utils/request');

Page({
  data: {
    orderId: '',
    totalPrice: 0,
    paymentMethod: '',
    showPaymentSuccess: false, // 控制支付成功提示是否显示
    countdown: 5 // 倒计时秒数
  },

  onLoad(options) {
    this.setData({
      orderId: options.orderId,
      totalPrice: options.totalPrice
    });
  },

  // 确认付款逻辑
  async confirmPayment() {
    const { orderId } = this.data;
    wx.showLoading({
      title: '支付中...',
    });

    request({
      url: `/order/${orderId}/pay`,
      method: 'POST',
      showLoading: false
    })
    .then((res) => {
      if (res) {
        this.handlePaymentSuccess();
      } else {
        console.error('支付失败');
      }
    })
    .finally(() => {
      // 在请求完成（成功或失败）时关闭加载提示
      wx.hideLoading(); 
    });
  },
  // 处理支付成功逻辑
  handlePaymentSuccess() {
    this.setData({
      showPaymentSuccess: true,
      countdown: 5
    });

    const timer = setInterval(() => {
      const { countdown } = this.data;
      if (countdown > 1) {
        this.setData({
          countdown: countdown - 1
        });
      } else {
        clearInterval(timer);
        this.backToOrder();
      }
    }, 1000);
  },

  // 立即返回订单
  backToOrder() {
    // 存储支付成功标志
    wx.setStorageSync('paymentSuccess', true);
    wx.navigateBack();
  }
});